<template>
  <el-form
    :label-position="labelPosition"
    label-width="auto"
    :model="form"
    style="max-width: 600px"
  >
    <el-form-item label="员工姓名" :label-position="itemLabelPosition">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="性别" :label-position="itemLabelPosition">
      <el-select
        v-model="form.sex"
        placeholder="Select"
        size="large"
        style="width: 240px"
      >
        <el-option key="男" label="男" value="男"/>
        <el-option key="女" label="女" value="女"/>
    </el-select>
    </el-form-item>
    <el-form-item label="年龄" :label-position="itemLabelPosition">
      <el-input-number v-model="form.age" />
    </el-form-item>
  </el-form>
  <el-button type="success" @click="cancel">取消</el-button>
  <el-button type="primary" @click="saveOrUpdate">
    {{ form.id ? '修改' : '保存' }}
  </el-button>
</template>

<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import type { FormItemProps, FormProps } from 'element-plus'
import {savePerson,updatePerson} from '../api'
import router from '../router'
import { ElMessage } from 'element-plus'

const labelPosition = ref<FormProps['labelPosition']>('right')
const itemLabelPosition = ref<FormItemProps['labelPosition']>('')

interface Person {
    id:number
    name: string
    sex: string
    age: number
  }

let form:Person = reactive({
  id: 0,
  name: '',
  sex: '男',
  age: 1,
})

//加载后接收数据
onMounted(() => {
  const data = history.state.params
  if (data) {
    //转换类型
    const person:Person = JSON.parse(data)
    //赋值
    form = person
  }

})

const saveEmployee = () => {
  savePerson(form)
  form = {} as Person
}

const updateEmployee = () => {
  updatePerson(form)
  form = {} as Person
}

const saveOrUpdate = () => {
  if (form.id) {
    updateEmployee()
  }
  else{
    saveEmployee()
  }
  ElMessage({
      message:' 操作成功',
      type: 'success',      
    })
 router.push({ path: '/person' })
}

const cancel = () => {}
</script>